package com.redxiii.spike.pmi.command;

import java.util.Set;

import com.redxiii.spike.api.command.CommandFactory;
import com.redxiii.spike.api.command.InitializationRequired;
import com.redxiii.spike.api.message.ImMessage;
import com.redxiii.spike.api.pmi.entity.Issue;
import com.redxiii.spike.pmi.HandlerSession;
import com.redxiii.spike.pmi.commons.UserSettings;
import com.redxiii.spike.util.command.InternetCommand;
import com.redxiii.spike.util.message.BasicMsgInterpreter;

/**
 * @author Daniel Filgueiras
 * @since 19/06/2011
 */
@CommandFactory(BasicMsgInterpreter.class)
@InitializationRequired
public class StartWork extends InternetCommand {

	private String issueId;
	private String expression;

	private static final String expSequence = "(?i)this|first|second|last";
	
	private static final String ERROR_UNKNOW_ISSUE = "Unknown issue";
	private static final String ERROR_EMPTY_ISSUE_LST = "Empty issue list. Search for any issues first!";
	
	enum IssueOrder {
		THIS,
		FIRST,
		SECOND,
		LAST,
	}
	
	@Override
	public boolean proccess(ImMessage message) {
		
		Issue issue = null;
		long issueNumber = -1;
		
		UserSettings settings = HandlerSession.getUserSettings(remoteId);
		
		if (expression != null && expression.matches(expSequence)) {
			
			Set<Long> issues = settings.getIssuesList();
			IssueOrder order = IssueOrder.valueOf(expression.toUpperCase());
			
			if (issues.size() == 0) {
				service.reply(message, ERROR_EMPTY_ISSUE_LST);
			} else if (issues.size() < 2 && order.equals(IssueOrder.SECOND)) { 
				service.reply(message, ERROR_UNKNOW_ISSUE);
			} else {
				Long[] aIssues = issues.toArray(new Long[]{});
				
				switch (order) {
					case THIS:
					case FIRST:
						issueNumber = aIssues[0];
						break;
					
					case SECOND:
						issueNumber = aIssues[1];
						break;
						
					case LAST:
						issueNumber = aIssues[aIssues.length-1];
						break;
				}
				
				issue = HandlerSession.getDatabase().getIssue(issueNumber);
			}
			
		} else if (issueId != null && issueId.matches("(\\d+)")) {
			issueNumber = Integer.parseInt(issueId);
			
			issue = HandlerSession.getDatabase().getIssue(issueNumber);
		}
		
		if (issue != null) {
			
			settings.setWorkingIssue(issueNumber);
			settings.setWorkingStartTime(System.currentTimeMillis());
			settings.setWorkedTime(0);
			
			StringBuilder builder =	new StringBuilder()
					.append("Accepted. Issue: *\"")
					.append(issue.getSummary())
					.append("\"*\r\n")
					.append("Check your working time: \"Worked time?\"");
			
			service.reply(message, builder);
		} else {
			service.reply(message, ERROR_UNKNOW_ISSUE);
		}

		return true;
	}
	

}
